package cn.aixuxi.security.controller;

import cn.aixuxi.security.constant.SysConstant;
import cn.aixuxi.security.entity.SysPermission;
import cn.aixuxi.security.entity.SysRole;
import cn.aixuxi.security.entity.SysRolePermission;
import cn.aixuxi.security.entity.SysUserRole;
import cn.aixuxi.security.service.SysPermissionService;
import cn.aixuxi.security.service.SysRolePermissionService;
import cn.aixuxi.security.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 类描述
 *
 * @author ruozhuliufeng
 * @version 1.0
 * @date 2021/4/22 22:22
 */
@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysRolePermissionService rolePermissionService;

    @Autowired
    private SysPermissionService permissionService;
    @GetMapping("index")
    public String index(Model model){
        List<SysRole> roleList = roleService.list();
        model.addAttribute("roleList",roleList);
        Integer roleCount = roleService.count();
        model.addAttribute("roleCount",roleCount);
        // 权限列表
        List<SysPermission> permissionList = permissionService.list();
        model.addAttribute("permissionList",permissionList);
        return "role";
    }
    @PostMapping("add")
    public String add(SysRole role){
        roleService.save(role);
        // 刷新页面
        return "redirect:/role/index";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable("id") Integer id, Model model){
        SysRole role = roleService.getById(id);
        model.addAttribute("updateRole",role);
        return "role_update";
    }

    @PostMapping("update")
    public String update(SysRole role){
        // 设置角色的前缀
        role.setRole(SysConstant.ROLE_PERFIX+role.getRole());
        role.setAvailable(SysConstant.AVAILABLE);
        roleService.save(role);
        // 刷新页面
        return "redirect:/role/index";
    }
    @GetMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        roleService.removeById(id);
        // 刷新页面
        return "redirect:/role/index";
    }

    @PostMapping("addPermission")
    public String addPermission(SysRolePermission rolePermission){
        // 保存或更新
        rolePermissionService.saveOrUpdate(rolePermission);
        // 刷新页面
        return "redirect:/role/index";
    }

}
